package cc.rengu.igas.share.core.service.trans;

import cc.rengu.igas.share.common.enums.RespCodeEnum;
import cc.rengu.igas.share.core.service.base.NoticeService;
import cc.rengu.igas.share.facade.request.UpqcC2bTransNoticeRequest;
import cc.rengu.igas.share.facade.response.UpqcC2bTransNoticeResponse;
import cc.rengu.oltp.service.common.constant.AppParamConstant;
import cc.rengu.oltp.service.common.constant.TreeNodeConstant;
import cc.rengu.oltp.service.common.entity.UserOrderInfo;
import cc.rengu.oltp.service.common.enums.BizStatusEnum;
import cc.rengu.oltp.service.common.enums.LimitTypeEnum;
import cc.rengu.oltp.service.common.enums.OrderStatusEnum;
import cc.rengu.oltp.service.common.enums.TransStatusEnum;
import cc.rengu.oltp.service.model.BizException;
import cc.rengu.oltp.service.model.BizResponse;
import cc.rengu.oltp.service.model.OrderInfo;
import cc.rengu.oltp.service.model.TransLimitInfo;
import cc.rengu.oltp.service.realize.OrderService;
import cc.rengu.oltp.service.realize.TransLimitService;
import cc.rengu.oltp.service.realize.impl.OrderServiceImpl;
import cc.rengu.oltp.service.realize.impl.TransLimitServiceImpl;
import cc.rengu.oltp.utility.util.*;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import org.apache.commons.codec.binary.Base64;

import java.util.ArrayList;
import java.util.List;

/**
 * 银联二维码－银联发起付款通知服务，基于原交易类型进行业务判断
 * 消费交易：0310000903          预授权冲正交易：0290100903
 * 消费冲正交易：0320000903      预授权撤销交易：0370000903
 * 消费撤销交易：0330000903      预授权完成交易：0380000903
 * 退货交易：0340000903         预授权完成冲正交易：0380100903
 * 预授权交易：0290000903       预授权完成撤销交易：0390000903
 */
public class UpqcC2BPayNoticeService extends NoticeService {

    @Override
    protected Object bizBeforeCust() throws Exception {
        XmlTreeUtil xmlTreeUtil = new XmlTreeUtil();
        UpqcC2bTransNoticeRequest upqcC2bTransNoticeRequest = new UpqcC2bTransNoticeRequest();
        ConvertUtil.convertOutput(upqcC2bTransNoticeRequest);
        xmlTreeUtil.setXmlTreeStringValue(TreeNodeConstant.FRONT_SEQ_NUM, upqcC2bTransNoticeRequest.getSettleKey());
        return upqcC2bTransNoticeRequest;
    }

    @Override
    protected BizResponse bizProcessCust(Object request) throws Exception {
        UpqcC2bTransNoticeRequest upqcC2bTransNoticeRequest = (UpqcC2bTransNoticeRequest) request;
        String instId = upqcC2bTransNoticeRequest.getHeader().getInstId();
        UpqcC2bTransNoticeResponse upqcC2bTransNoticeResponse = new UpqcC2bTransNoticeResponse();
        upqcC2bTransNoticeResponse.setHeader(upqcC2bTransNoticeRequest.getHeader());
        /* 根据订单号获取原支付交易订单信息 */
        String deBase64Str = new String(Base64.decodeBase64(upqcC2bTransNoticeRequest.getReqReserved()));
        JSONObject reqResJson = JSON.parseObject(deBase64Str);
        OrderService orderService = new OrderServiceImpl();
        OrderInfo orderInfo = orderService.selectOrderInfoBySysSeqNum(instId, reqResJson.getString("flowNo"));
        if (null == orderInfo) {
            rglog.debug("银联通知查询订单信息异常, 订单保留信息:{}", upqcC2bTransNoticeRequest.getReqReserved());
            throw new BizException(RespCodeEnum.ORDER_NOT_EXIST.getRespCode(), RespCodeEnum.ORDER_NOT_EXIST.getRespDesc());
        }
        UserOrderInfo userOrderInfo = orderInfo.getUserOrderInfo();

        //用户订单终态，且请求类型为 消费交易 、预授权交易 、预授权完成交易的将不在进行异步通知处理
        if (("0310000903".equals(upqcC2bTransNoticeRequest.getOrigReqType())
                || "0290000903".equals(upqcC2bTransNoticeRequest.getOrigReqType()))
                && TransStatusEnum.TRANS_SUCC.getStatus().equals(userOrderInfo.getTransStatus())) {
            rglog.debug("订单状态已经完成，不需要更新订单信息!");
            throw new BizException(RespCodeEnum.ORDER_PAY_FINISH.getRespCode(), RespCodeEnum.ORDER_PAY_FINISH.getRespDesc());
        }

        // 更新用户订单状态为03-订单已完成
        userOrderInfo.setOrderStatus(OrderStatusEnum.FINISH.getStatus());

        //根据原交易状态更新用户订单信息
        if ("00".equals(upqcC2bTransNoticeRequest.getOrigRespCode())) {
            //原交易交易成功
            if ("0310000903".equals(upqcC2bTransNoticeRequest.getOrigReqType())
                    || "0290000903".equals(upqcC2bTransNoticeRequest.getOrigReqType())
                    || "0380000903".equals(upqcC2bTransNoticeRequest.getOrigReqType())) {
                //消费交易：0310000903,预授权交易：0290000903,预授权完成交易：0380000903
                userOrderInfo.setTransStatus(TransStatusEnum.TRANS_SUCC.getStatus());
                userOrderInfo.setBizStatus(BizStatusEnum.FINISH.getStatus());
                userOrderInfo.setFrontSeqNum(upqcC2bTransNoticeRequest.getVoucherNum());
                userOrderInfo.setGroupMchntNo(upqcC2bTransNoticeRequest.getCupsMchntNo());
                userOrderInfo.setGroupMchntName(upqcC2bTransNoticeRequest.getMchntName());
            } else if ("0320000903".equals(upqcC2bTransNoticeRequest.getOrigReqType())
                    || "0290100903".equals(upqcC2bTransNoticeRequest.getOrigReqType())
                    || "0380100903".equals(upqcC2bTransNoticeRequest.getOrigReqType())) {
                //消费冲正交易：0320000903,预授权冲正交易：0290100903,预授权完成冲正交易：0380100903
                userOrderInfo.setBizStatus(BizStatusEnum.REVSAL.getStatus());
            } else if ("0330000903".equals(upqcC2bTransNoticeRequest.getOrigReqType())
                    || "0370000903".equals(upqcC2bTransNoticeRequest.getOrigReqType())
                    || "0390000903".equals(upqcC2bTransNoticeRequest.getOrigReqType())) {
                //消费撤销交易：0330000903,预授权撤销交易：0370000903,预授权完成撤销交易：0390000903
                userOrderInfo.setBizStatus(BizStatusEnum.CANCEL.getStatus());
            } else if ("0340000903".equals(upqcC2bTransNoticeRequest.getOrigReqType())) {
                //退货交易：0340000903
                userOrderInfo.setBizStatus(BizStatusEnum.REFUND.getStatus());
            }
        } else if (!"00".equals(upqcC2bTransNoticeRequest.getOrigRespCode())) {
            //原交易交易失败
            userOrderInfo.setTransStatus(TransStatusEnum.SYSTEM_REJECT.getStatus());
            if ("0310000903".equals(upqcC2bTransNoticeRequest.getOrigReqType())
                    || "0290000903".equals(upqcC2bTransNoticeRequest.getOrigReqType())
                    || "0380000903".equals(upqcC2bTransNoticeRequest.getOrigReqType())) {
                //消费交易：0310000903,预授权交易：0290000903,预授权完成交易：0380000903
                userOrderInfo.setBizStatus(BizStatusEnum.FAILED.getStatus());
                userOrderInfo.setFrontSeqNum(upqcC2bTransNoticeRequest.getVoucherNum());
                userOrderInfo.setGroupMchntNo(upqcC2bTransNoticeRequest.getCupsMchntNo());
                userOrderInfo.setGroupMchntName(upqcC2bTransNoticeRequest.getMchntName());
            }
            //将错误信息保存在附件信息中
            JSONObject orderExtraInfo = new JSONObject();
            if (!StringUtil.isEmptyOrNull(userOrderInfo.getOrderExtraInfo())) {
                orderExtraInfo = JSON.parseObject(userOrderInfo.getOrderExtraInfo());
            }
            orderExtraInfo.put("errorCode", upqcC2bTransNoticeRequest.getOrigRespCode());
            orderExtraInfo.put("errorMsg", upqcC2bTransNoticeRequest.getOrigRespDesc());
            userOrderInfo.setOrderExtraInfo(JSON.toJSONString(orderExtraInfo));
        }

        userOrderInfo.setUpdateTime(DateUtil.getCurrentDateTime("yyyy-MM-dd HH:mm:ss.SSS"));
        // 消费交易0310000903
        if (("0310000903".equals(upqcC2bTransNoticeRequest.getOrigReqType())
                || "0290000903".equals(upqcC2bTransNoticeRequest.getOrigReqType())
                || "0380000903".equals(upqcC2bTransNoticeRequest.getOrigReqType()))
                && "00".equals(upqcC2bTransNoticeRequest.getOrigRespCode())) {
            if (!StringUtil.isEmptyOrNull(userOrderInfo.getRealPayAmt())
                    && !userOrderInfo.getRealPayAmt().equals(upqcC2bTransNoticeRequest.getOrderAmt())) {
                rglog.debug("预下单金额和通知金额不一致，预下单金额<{}>, 通知金额<{}>。", userOrderInfo.getRealPayAmt(), upqcC2bTransNoticeRequest.getOrderAmt());
                throw new BizException(RespCodeEnum.TRANS_AMT_MISMATCH.getRespCode(), RespCodeEnum.TRANS_AMT_MISMATCH.getRespDesc());
            } else {
                userOrderInfo.setOrderAmt(upqcC2bTransNoticeRequest.getOrderAmt());
                userOrderInfo.setRealPayAmt(upqcC2bTransNoticeRequest.getOrderAmt());
                userOrderInfo.setOrderCcy(upqcC2bTransNoticeRequest.getOrderCcy());
                userOrderInfo.setNeedPayAmt(upqcC2bTransNoticeRequest.getOrderAmt());
            }
        }

        // 优惠信息是否为空
        if (!StringUtil.isEmptyOrNull(upqcC2bTransNoticeRequest.getCouponInfoStr())) {
            userOrderInfo.setOrderAmt(upqcC2bTransNoticeRequest.getOrigTxnAmt());
            userOrderInfo.setNeedPayAmt(upqcC2bTransNoticeRequest.getOrigTxnAmt());
            String couponInfoStr = new String(Base64.decodeBase64(upqcC2bTransNoticeRequest.getCouponInfoStr()));
            userOrderInfo.setDiscountInfo(couponInfoStr);
            rglog.debug("优惠券信息：<{}>", couponInfoStr);
        }

        userOrderInfo.setOrigSysSeqNum(upqcC2bTransNoticeRequest.getOrigReqType());
        userOrderInfo.setOrderCcy("156");

        // 更新状态
        boolean bROrderCode = orderService.updateOrderInfo(userOrderInfo, null, null);
        if (!bROrderCode) {
            rglog.error("被扫二维码通知 更新用户订单表失败!");
            throw new BizException(RespCodeEnum.ORDER_UPDATE_ERROR.getRespCode(), RespCodeEnum.ORDER_UPDATE_ERROR.getRespDesc());
        }

        // 不成功不更新限额
        if (!"00".equals(upqcC2bTransNoticeRequest.getOrigRespCode())) {
            BizResponse bizResponse = new BizResponse();
            bizResponse.setResult(upqcC2bTransNoticeResponse);
            bizResponse.setRspSysId(AppParamConstant.IGAS);
            bizResponse.setRespCode(RespCodeEnum.TRANS_SUCCESS.getRespCode());
            bizResponse.setRespDesc(RespCodeEnum.TRANS_SUCCESS.getRespDesc());
            return bizResponse;
        }

        // 更新用户累计限额
        TransLimitInfo transLimitInfo = new TransLimitInfo();
        transLimitInfo.setInstId(instId);
        transLimitInfo.setLimitInst(userOrderInfo.getInstId() + "|" + userOrderInfo.getInstId() + "|" + userOrderInfo.getUserId());
        transLimitInfo.setLimitAcctType("*");
        if ("0250000903".equals(upqcC2bTransNoticeRequest.getReqType())) {
            // 0250000903:被扫
            if (!"0310000903".equals(upqcC2bTransNoticeRequest.getOrigReqType())
                    && !"0290000903".equals(upqcC2bTransNoticeRequest.getOrigReqType())
                    && !"0380000903".equals(upqcC2bTransNoticeRequest.getOrigReqType())) {
                // 消费交易：0310000903,预授权交易：0290000903,预授权完成交易：0380000903
                BizResponse bizResponse = new BizResponse();
                bizResponse.setResult(upqcC2bTransNoticeResponse);
                bizResponse.setRspSysId(AppParamConstant.IGAS);
                bizResponse.setRespCode(RespCodeEnum.TRANS_SUCCESS.getRespCode());
                bizResponse.setRespDesc(RespCodeEnum.TRANS_SUCCESS.getRespDesc());
                return bizResponse;
            }
            // 限额类型 42-被扫
            transLimitInfo.setLimitType(LimitTypeEnum.C2B_QR.getLimitType());
        } else if ("014000903".equals(upqcC2bTransNoticeRequest.getReqType())
                && "0".equals(userOrderInfo.getRemark1())) {
            // 限额类型 主扫动态码 动态码按照和被扫累计在一块,主扫 二维码类型 0：动态码 1：静态码
            transLimitInfo.setLimitType(LimitTypeEnum.C2B_QR.getLimitType());
        } else {
            // 限额类型 主扫静态码
            transLimitInfo.setLimitType(LimitTypeEnum.B2C_STATIC.getLimitType());
        }
        // 需要验证
        transLimitInfo.setDayLimitAmt("0");
        List<TransLimitInfo> transLimitInfoList = new ArrayList<>();
        transLimitInfoList.add(transLimitInfo);

        // 静态码也需要累计到二维码限额中
        if ("014000903".equals(upqcC2bTransNoticeRequest.getReqType()) && "1".equals(userOrderInfo.getRemark1())) {
            TransLimitInfo transLimitInfo2 = new TransLimitInfo();
            BeanUtil.beanCopy(transLimitInfo, transLimitInfo2);
            transLimitInfo2.setLimitType(LimitTypeEnum.C2B_QR.getLimitType());
            transLimitInfoList.add(transLimitInfo2);
        }
        // 更新累计限额
        TransLimitService transLimitService = new TransLimitServiceImpl(instId, txnInfo.getSrcTxnAuthCfg().getTxnNum(), null);
        if (!transLimitService.transLimitStatis(userOrderInfo.getRealPayAmt(), transLimitInfoList)) {
            rglog.error("收到通知，累计限额失败，已经扣款，不做处理，需关注。订单号<{}>", userOrderInfo.getSysSeqNum());
        }

        // 组装返回报文
        BizResponse bizResponse = new BizResponse();
        bizResponse.setResult(upqcC2bTransNoticeResponse);
        bizResponse.setRspSysId(AppParamConstant.IGAS);
        bizResponse.setRespCode(RespCodeEnum.TRANS_SUCCESS.getRespCode());
        bizResponse.setRespDesc(RespCodeEnum.TRANS_SUCCESS.getRespDesc());
        return bizResponse;
    }

    @Override
    protected void bizAfterCust(Object response) throws Exception {
        BizResponse bizResponse = (BizResponse) response;
        UpqcC2bTransNoticeResponse upqcC2bTransNoticeResponse = (UpqcC2bTransNoticeResponse) bizResponse.getResult();
        ConvertUtil.convertInput(upqcC2bTransNoticeResponse);
    }
}
